package com.adong.tv.ui.fragment;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.leanback.app.BrowseSupportFragment;
import androidx.leanback.app.SearchFragment;
import androidx.leanback.app.SearchSupportFragment;
import androidx.leanback.widget.ArrayObjectAdapter;
import androidx.leanback.widget.HeaderItem;
import androidx.leanback.widget.ListRow;
import androidx.leanback.widget.ListRowPresenter;
import androidx.leanback.widget.OnItemViewClickedListener;
import androidx.leanback.widget.OnItemViewSelectedListener;
import androidx.leanback.widget.Presenter;
import androidx.leanback.widget.Row;
import androidx.leanback.widget.RowPresenter;
import androidx.leanback.widget.VerticalGridPresenter;
import androidx.lifecycle.ViewModelProvider;

import com.adong.tv.R;
import com.adong.tv.data.ApiConfig;
import com.adong.tv.model.ApiSource;
import com.adong.tv.model.Category;
import com.adong.tv.model.Movie;
import com.adong.tv.ui.DetailActivity;
import com.adong.tv.ui.presenter.ApiPresenter;
import com.adong.tv.ui.presenter.MovieCardPresenter;
import com.adong.tv.ui.viewmodel.MainViewModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主界面Fragment
 */
public class MainFragment extends BrowseSupportFragment {
    
    private static final int CATEGORY_ALL = 0;
    private static final int SEARCH_RESULTS_CATEGORY_ID = 0;

    private MainViewModel viewModel;
    private ArrayObjectAdapter rowsAdapter;

    private SearchSupportFragment mSearchFragment;

    private final Map<Integer, ArrayObjectAdapter> categoryAdapters = new HashMap<>();

    /**
     * 搜索图标提供者
     */
//    private final class SearchAffordanceProvider extends BrowseSupportFragment.SearchAffordanceProvider {
//        @Override
//        public Drawable getIcon() {
//            return ContextCompat.getDrawable(getContext(), R.drawable.ic_search);
//        }
//    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        viewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
        setupUI();
        setupEventListeners();
        loadData();
    }

    /**
     * 设置UI
     */
    private void setupUI() {
        // 设置标题
        setTitle(getString(R.string.app_name));

        // 设置搜索功能
        setHeadersState(HEADERS_ENABLED);
        setHeadersTransitionOnBackEnabled(false);

        // 设置背景
        setBrandColor(ContextCompat.getColor(requireContext(), R.color.primary_dark));

        // 设置适配器
        rowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
        setAdapter(rowsAdapter);

        // 添加搜索框
//        setSearchAffordanceColor(ContextCompat.getColor(requireContext(), R.color.gray));
//        enableSearchIcon(true);
    }

    /**
     * 启用或禁用搜索图标
     */
    private void enableSearchIcon(boolean enable) {
        if (enable) {
            setSearchAffordanceColor(ContextCompat.getColor(requireContext(), R.color.search_color));
//            setSearchAffordanceProvider(new SearchAffordanceProvider());
        } else {
            setSearchAffordanceColor(ContextCompat.getColor(requireContext(), R.color.gray));
        }
    }

    /**
     * 设置事件监听器
     */
    private void setupEventListeners() {
        // 设置点击事件
        setOnItemViewClickedListener(new OnItemViewClickedListener() {
            @Override
            public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
                if (item instanceof Movie) {
                    Movie movie = (Movie) item;
                    Intent intent = new Intent(getActivity(), DetailActivity.class);
                    intent.putExtra(DetailActivity.EXTRA_MOVIE_ID, movie.getVodId());
                    startActivity(intent);
                } else if (item instanceof ApiSource) {
//                    ApiSource apiSource = (ApiSource) item;
//                    viewModel.switchApiSource(apiSource);
//                    Toast.makeText(getContext(), "已切换到 " + apiSource.getDesc() + " 数据源", Toast.LENGTH_SHORT).show();
//
//                    // 刷新数据
//                    loadData();
                }
            }
        });

        // 添加搜索框
        setOnSearchClickedListener(view -> {
            // 显示搜索对话框
            showSearchDialog();
        });

        // 设置选择事件
        setOnItemViewSelectedListener(new OnItemViewSelectedListener() {
            @Override
            public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) {
                if (item instanceof Movie) {
                    // 可以在这里处理预览或其他效果
                }
            }
        });
    }

    /**
     * 显示搜索对话框
     */
    private void showSearchDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("搜索");

        // 创建自定义布局
        View view = getLayoutInflater().inflate(R.layout.dialog_search, null);
        final EditText input = view.findViewById(R.id.edit_search);

        // 设置输入类型为普通文本，支持中文输入
        input.setInputType(android.text.InputType.TYPE_CLASS_TEXT);

        builder.setView(view);

        // 设置按钮
        builder.setPositiveButton("搜索", (dialog, which) -> {
            String keyword = input.getText().toString().trim();
            if (!keyword.isEmpty()) {
                performSearch(keyword);
            }
        });
        builder.setNegativeButton("取消", (dialog, which) -> dialog.cancel());

        AlertDialog dialog = builder.create();

        // 设置键盘按钮点击监听
        input.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == android.view.inputmethod.EditorInfo.IME_ACTION_SEARCH) {
                String keyword = input.getText().toString().trim();
                if (!keyword.isEmpty()) {
                    performSearch(keyword);
                    dialog.dismiss();
                    return true;
                }
            }
            return false;
        });

        dialog.show();
    }

    /**
     * 执行搜索
     * @param keyword 搜索关键字
     */
    private void performSearch(String keyword) {
        // 设置搜索关键字
        viewModel.setSearchKeyword(keyword);
        viewModel.setSelectedCategory(null); // 搜索时不需要分类ID

        // 显示加载提示
        Toast.makeText(getContext(), "正在搜索: " + keyword, Toast.LENGTH_SHORT).show();

        // 搜索电影
        viewModel.getSearchList(1).observe(getViewLifecycleOwner(), result -> {
            if (result.isSuccess() && result.getData() != null) {
                // 移除之前的搜索结果行（如果有）
                for (int i = 0; i < rowsAdapter.size(); i++) {
                    Object item = rowsAdapter.get(i);
                    if (item instanceof ListRow) {
                        ListRow row = (ListRow) item;
                        if (row.getHeaderItem().getId() == SEARCH_RESULTS_CATEGORY_ID) {
                            rowsAdapter.remove(item);
                            break;
                        }
                    }
                }

                // 添加搜索结果行
                if (!result.getData().isEmpty()) {
                    HeaderItem header = new HeaderItem(SEARCH_RESULTS_CATEGORY_ID, "搜索结果: " + keyword);
                    ArrayObjectAdapter adapter = new ArrayObjectAdapter(new MovieCardPresenter());

                    for (Movie movie : result.getData()) {
                        adapter.add(movie);
                    }

                    ListRow searchRow = new ListRow(header, adapter);
                    rowsAdapter.add(0, searchRow); // 添加到顶部

                    // 滚动到顶部
                    setSelectedPosition(0);
                } else {
                    // 没有搜索结果
                    Toast.makeText(getContext(), "没有找到相关结果", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "搜索失败: " + result.getMessage(), Toast.LENGTH_SHORT).show();
            }

            // 清除搜索关键字，以便下次正常加载分类内容
            viewModel.setSearchKeyword(null);
            viewModel.setSelectedCategory(CATEGORY_ALL);
        });
    }

    /**
     * 加载数据
     */
    private void loadData() {
        // 清除现有的电影行
        List<ListRow> rowsToRemove = new ArrayList<>();
        for (int i = 0; i < rowsAdapter.size(); i++) {
            Object item = rowsAdapter.get(i);
            if (item instanceof ListRow) {
                ListRow row = (ListRow) item;
                if (row.getHeaderItem().getId() != 0) { // 不是API源行
                    rowsToRemove.add(row);
                }
            }
        }

        for (ListRow row : rowsToRemove) {
            rowsAdapter.remove(row);
        }

        categoryAdapters.clear();

        // 加载分类
        viewModel.getCategories().observe(getViewLifecycleOwner(), result -> {
            // 打印 result 数据
            Log.d("MainFragment", "loadData: " + result.getData());
            if (result.isSuccess() && result.getData() != null) {
                setupCategories(result.getData());
            } else {
                Toast.makeText(getContext(), "加载分类失败: " + result.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 设置分类
     * @param categories 分类列表
     */
    private void setupCategories(List<Category> categories) {
        // 添加"全部"分类
//        HeaderItem allHeader = new HeaderItem(CATEGORY_ALL, "全部");
//        ArrayObjectAdapter allAdapter = new ArrayObjectAdapter(new MovieCardPresenter());
//        categoryAdapters.put(CATEGORY_ALL, allAdapter);
//        rowsAdapter.add(new ListRow(allHeader, allAdapter));

        // 添加顶级分类
        for (Category category : categories) {
            if (category.getTypePid() != 0) {
                HeaderItem header = new HeaderItem(category.getTypeId(), category.getTypeName());
                ArrayObjectAdapter adapter = new ArrayObjectAdapter(new MovieCardPresenter());
                categoryAdapters.put(category.getTypeId(), adapter);
                rowsAdapter.add(new ListRow(header, adapter));
            }
        }

        // 加载各分类的影片
        loadMoviesByCategory(CATEGORY_ALL);
        for (Category category : categories) {
            if (category.getTypePid() != 0) {
                loadMoviesByCategory(category.getTypeId());
            }
        }
    }

    /**
     * 按分类加载影片
     * @param categoryId 分类ID
     */
    private void loadMoviesByCategory(int categoryId) {
        viewModel.setSelectedCategory(categoryId);
        viewModel.getMovieList(1).observe(getViewLifecycleOwner(), result -> {
            if (result.isSuccess() && result.getData() != null) {
                ArrayObjectAdapter adapter = categoryAdapters.get(CATEGORY_ALL);
                if (adapter != null) {
                    adapter.clear();
                    for (Movie movie : result.getData()) {
                        adapter.add(movie);
                    }
                }

                // 根据类型分类影片
                for (Movie movie : result.getData()) {
                    int typeId = movie.getTypeId();
                    if (categoryAdapters.containsKey(typeId)) {
                        ArrayObjectAdapter typeAdapter = categoryAdapters.get(typeId);
                        if (typeAdapter != null) {
                            typeAdapter.add(movie);
                        }
                    }
                }
            } else {
                Toast.makeText(getContext(), "加载影片失败: " + result.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
} 